package com.pandora.credit.service.impl;

import com.pandora.common.util.Constants;
import com.pandora.common.util.MagicConst;
import com.pandora.common.util.RegexUtil;
import com.pandora.common.util.VerifyUtil;
import com.pandora.credit.dao.VersionDao;
import com.pandora.credit.dto.response.SwitchResponse;
import com.pandora.credit.entity.Version;
import com.pandora.credit.service.VersionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author developer
 */
@Service
public class VersionServiceImpl implements VersionService {
    private static final String REGX = "PandoraCredit/(.*?)\\(";
    @Autowired
    private VersionDao versionDao;

    @Override
    @Cacheable(value = "version")
    public Integer getStatusByType(String platform, String version, int valid) {
        List<Version> vs = versionDao.queryByPvv(platform, version, valid);
        if (vs == null || vs.size() <= 0) {
            return -1;
        } else {
            return vs.get(0).getStatus();
        }
    }

    @Override
    public List<Version> queryList(String platform, String version, int valid) {
        return versionDao.queryList(platform, version, valid);
    }

    @Override
    public void save(Version version) {
        versionDao.insert(version);
    }

    @Override
    public void update(Version version) {
        versionDao.update(version);
    }

    @Override
    public SwitchResponse requestSwitch(String ua) {
        int value = Constants.VERSION_STATUS_ONLINE;
        if (!VerifyUtil.isEmpty(ua)) {
            String v = null;
            List<String> li = RegexUtil.findAllReg(REGX, ua);
            if (li.size() > 0) {
                v = li.get(0);
            }
            String p = null;
            if (ua.contains(MagicConst.AGENT_OK_HTTP)) {
                p = "android";
            }
            if (ua.contains(MagicConst.AGENT_ALAMO_FIRE)) {
                p = "ios";
            }
            if (!VerifyUtil.isEmpty(p) && !VerifyUtil.isEmpty(v)) {
                int status = getStatusByType(p, v, Constants.ITEM_STATUS_VALID);
                if (status > 0) {
                    value = status;
                }
            }
        }
        return new SwitchResponse(value);
    }
}
